﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using WCFMINERP.COM;
using WCFMINERP.Contracts.DataContracts;
using WCFMINERP.DisjoinProForOutShop.Iview;
using WCFMINERP.DisjoinProForOutShop.Presenter;
using WCFMINERP.InnerFactoryContracts.DataContracts;
using WCFMINERP.PrintShopBill.Presenter;

namespace WCFMINERP.DisjoinProForOutShop.Forms
{
    public partial class FrmMain : Form,IMainView
    {

        LatticePartitionPresenter _LatticePartition = new LatticePartitionPresenter();
        MainPresenter _presenter;
        Speech speech = new Speech();

        /// <summary>
        /// 当前点击选中的格子，
        /// </summary>
        Lattice EliminateLattice = new Lattice();

        public FrmMain()
        {
            InitializeComponent();
            if (Properties.Settings.Default.FactoryId == 0)  //启动激活程序
            {
                FrmActive login = new FrmActive();
                login.ShowDialog();
            }

            InnterManagePresenter.FactoryId = Properties.Settings.Default.FactoryId;
            try
            {
                if (login())   //弹出登录框
                {
                    _presenter = new MainPresenter(this);
                }
                else
                {
                    Environment.Exit(-1);
                }
            }
            catch (Exception ex)
            {
                WriteAnalyseLog.WriteLogFile(ex.Message);
            }
        }
        void txt_Code_LostFocus(object sender, EventArgs e)
        {
            txt_Code.Focus();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        private bool login()
        {
            bool b = false;
            frmLogin login = new frmLogin();
            login.ShowDialog();

            if (InnterManagePresenter.UserInfo != null && InnterManagePresenter.UserInfo.UserId > 0)
            {
                b = true;
            }
            else
            {
                b = false;
            }
            return b;
        }

        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_Load(object sender, EventArgs e)
        {
            lbl_tisi.MaximumSize = new System.Drawing.Size(panelControl2.Width, 0);
            lbl_tisi.Text = "";
            splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel1;//先收缩右边的详细列表

            Pwidth = splitContainerControl1.Panel1.Width;
            Pheight = splitContainerControl1.Panel1.Height;

            Bind();
            if (!string.IsNullOrEmpty(Help.LatticePartitionID))
            {               
                Refreshdata(0, null);
            }
            GridHandle.ShopClick += GridHandle_ShopClick;
            GridHandle.ShopDoubleClick += GridHandle_ShopDoubleClick;
            //txt_Code.LostFocus+=txt_Code_LostFocus;
            txt_Code.Focus();
            but_Select.Tag = true;

        }

        void GridHandle_ShopDoubleClick(object shopUGrid)
        {

            ULattice control = shopUGrid as ULattice;
            Lattice model = control.Tag as Lattice;
            if (splitContainerControl1.PanelVisibility == SplitPanelVisibility.Both)
            {
                splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel1;//只显示panel1
                if (tableLayoutPanelOutOrder.HorizontalScroll.Visible)
                {
                    tableLayoutPanelOutOrder.AutoScroll = true;
                    tableLayoutPanelOutOrder.HorizontalScroll.Visible = false;
                }

            }
            else
            {
                splitContainerControl1.PanelVisibility = SplitPanelVisibility.Both;//两个都可见       
                if (!tableLayoutPanelOutOrder.HorizontalScroll.Visible)
                {
                    tableLayoutPanelOutOrder.AutoScroll = true;
                    tableLayoutPanelOutOrder.HorizontalScroll.Visible = true;
                }
                //Getdata();  //获取数据
                BindGridControl(model);
            }
            EliminateLattice = model;
        }

        void GridHandle_ShopClick(object shopUGrid)
        {
            ULattice UC = shopUGrid as ULattice;
            BindColor();
            UC.BackColor = UCClickColor;  //选中的颜色
            EliminateLattice = UC.Lattice as Lattice;
            BindGridControl(EliminateLattice);
        }
              
        /// <summary>
        /// 设置格子分区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_SetLatticePartition_Click(object sender, EventArgs e)
        {
            frmSetupLattice lattice = new frmSetupLattice();
            DialogResult dr=  lattice.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
               
            }

            Bind(); LoadControl();
        }

        private void LoadControl()
        {
            splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel1;//只显示panel1
            InitialOutShopGrid();
            BindColor();
            MapLocation();
        }

        int Pwidth =0; 
        int Pheight = 0;

        public Color UCPrintColor = Color.FromArgb(56, 210, 231);

        /// <summary>
        /// 格子已经有东西了
        /// </summary>
        public Color UCBackColor = Color.FromArgb(214, 246, 230);

        /// <summary>
        /// 格子默认颜色
        /// </summary>
        public Color UCBackDefultColor = Color.White;

        /// <summary>
        /// 选中一个格子之后的颜色
        /// </summary>
        public Color UCClickColor =Color.LightPink;// Color.FromArgb(42, 140, 3);

        /// <summary>
        /// 绑定颜色
        /// </summary>
        private void BindColor()
        {
            foreach (UserControl cont in tableLayoutPanelOutOrder.Controls)
            {
                if (cont is ULattice)
                {
                    ULattice itemControl = cont as ULattice;                    
                    if (itemControl._ExistenceNumber > 0)
                    {
                        if (itemControl._ExistenceNumber == itemControl._OrderNumber)
                        {
                            itemControl.BackColor = UCPrintColor;
                        }
                        else
                        {
                            itemControl.BackColor = UCBackColor;
                        }
                    }
                    else
                    {
                        itemControl.BackColor = UCBackDefultColor;
                    }
                }
            }
        }

        /// <summary>
        /// 加载格子
        /// </summary>
        public void InitialOutShopGrid()
        {
            if (InnterManagePresenter.latticePartitionModel != null)
            {
                LatticePartition subArea = InnterManagePresenter.latticePartitionModel;

                tableLayoutPanelOutOrder.AutoScroll = false;

                tableLayoutPanelOutOrder.Controls.Clear();
                tableLayoutPanelOutOrder.RowStyles.Clear();
                tableLayoutPanelOutOrder.ColumnStyles.Clear();

                tableLayoutPanelOutOrder.Width = subArea.ColumnNum * 167;
                tableLayoutPanelOutOrder.Height = subArea.RowsNum * 104;
                tableLayoutPanelOutOrder.Refresh();
                tableLayoutPanelOutOrder.Update();

                tableLayoutPanelOutOrder.AutoScrollMargin = new System.Drawing.Size(Pwidth, Pheight);
               
                int SerialNumber = 0;
                tableLayoutPanelOutOrder.RowCount = subArea.RowsNum;
                tableLayoutPanelOutOrder.ColumnCount = subArea.ColumnNum;
                int gWidth =  Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(Pwidth*1d / subArea.ColumnNum)));
                int gheight =Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(Pheight*1d / subArea.RowsNum)));
                int lableWidth = 0;
                for (var i = 0; i < tableLayoutPanelOutOrder.RowCount; i++)    //行
                {
                   int wh = 0;
                    if (gheight < 104)
                    {
                        wh = 104;// gheight;
                        tableLayoutPanelOutOrder.AutoScroll = true;
                        tableLayoutPanelOutOrder.VerticalScroll.Visible = true;
                    }
                    else
                    {
                        wh = gheight;
                        tableLayoutPanelOutOrder.VerticalScroll.Visible = false;
                       
                    }
                    tableLayoutPanelOutOrder.RowStyles.Add(new RowStyle(SizeType.Absolute, wh));
                }
                for (var i = 0; i < tableLayoutPanelOutOrder.ColumnCount; i++)  //列
                {
                    int wd = 0;
                    if (gWidth < 167)  //167, 104
                    {
                        wd = 167;// gWidth;
                        tableLayoutPanelOutOrder.AutoScroll = true;
                        tableLayoutPanelOutOrder.HorizontalScroll.Visible = true;
                    }
                    else
                    {
                        wd = gWidth;

                        tableLayoutPanelOutOrder.HorizontalScroll.Visible = false;
                       
                    }
                    lableWidth = wd;
                    tableLayoutPanelOutOrder.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, wd));
                }
               
                tableLayoutPanelOutOrder.SuspendLayout();
                for (int j = 0; j < subArea.RowsNum; j++)
                {
                    for (int i = 0; i < subArea.ColumnNum; i++)
                    {
                        ULattice latticeControl = new ULattice();
                        latticeControl._wd = lableWidth;                 
                        latticeControl.Dock = DockStyle.Fill;
                        SerialNumber++;
                        latticeControl._SerialNumber = SerialNumber;
                        if (subArea.listLattice != null)
                        {
                            Lattice mdoel = subArea.listLattice[SerialNumber - 1];
                            latticeControl.Name = mdoel.LatticeName.ToString();
                            latticeControl.Lattice = mdoel;
                            latticeControl.Tag = mdoel;
                            latticeControl._ExistenceNumber = mdoel.latticeRecordList.Count;
                            latticeControl._OrderNumber = mdoel.OrderInfoCount;
                        }
                        if (latticeControl._ExistenceNumber > 0)
                        {
                            if (latticeControl._ExistenceNumber == latticeControl._OrderNumber)
                            {
                                latticeControl.BackColor = UCPrintColor;
                            }
                            else
                            {
                                latticeControl.BackColor = UCBackColor;
                            }
                        }
                        else
                        {
                            latticeControl.BackColor = UCBackDefultColor;
                        }
                        //latticeControl.ShopClick += latticeControl_ShopClick;
                        //latticeControl.ShopDoubleClick += latticeControl_ShopDoubleClick;
                        tableLayoutPanelOutOrder.Controls.Add(latticeControl,i,j);
                        Lattice currLattice = (Lattice) latticeControl.Tag;
                        _dictionaryControl.Add(currLattice.LatticeID.ToString(), latticeControl);
                        tableLayoutPanelOutOrder.Update();
                    }
                }              
                tableLayoutPanelOutOrder.ResumeLayout();
            }
        }
        Dictionary<string,ULattice>_dictionaryControl=new Dictionary<string, ULattice>();
        /// <summary>
        /// 双击控件
        /// </summary>
        /// <param name="shopUGrid"></param>
        void latticeControl_ShopDoubleClick(ULattice shopUGrid)
        {
            ULattice control = shopUGrid as ULattice;
            Lattice model = control.Tag as Lattice;
            if (splitContainerControl1.PanelVisibility == SplitPanelVisibility.Both)
            {
                splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel1;//只显示panel1

            }
            else
            {
                splitContainerControl1.PanelVisibility = SplitPanelVisibility.Both;//两个都可见           
                tableLayoutPanelOutOrder.AutoScroll = true;
                Getdata();  //获取数据
                BindGridControl(model);
            }
            EliminateLattice = model;
        }

        private string GetStata(OrderInfo info)
        {
            switch ((OrderInfoStatus)info.Status)
            {
                case OrderInfoStatus.Doing: return "正在生产中";

                case OrderInfoStatus.Error: return "错误";

                case OrderInfoStatus.Stop: return "已暂停";

                case OrderInfoStatus.Completed: return "已完成";
                case OrderInfoStatus.WaitPay:
                    return "余额不足等待付款";
                case OrderInfoStatus.WaitPayAndWaitMovePhoto:
                case OrderInfoStatus.WaitPhotoMove:
                    return "正在移动照片";
                case OrderInfoStatus.Deleted: return "已删除";
                case OrderInfoStatus.AutoOrderWait: return "远程开单审核";
                default: return "未知，请在客服处查询";
            }
        }

        /// <summary>
        /// 单击控件
        /// </summary>
        /// <param name="shopUGrid"></param>
        void latticeControl_ShopClick(ULattice shopUGrid)
        {
            if (shopUGrid != null)
            {
                foreach (UserControl cont in tableLayoutPanelOutOrder.Controls)
                {
                    if (cont is ULattice)
                    {
                        ULattice itemControl = cont as ULattice;
                        ULattice control = shopUGrid as ULattice;
                        if (itemControl._ExistenceNumber > 0)
                        {
                            if (itemControl._ExistenceNumber == itemControl._OrderNumber)
                            {
                                itemControl.BackColor = UCPrintColor;
                            }
                            else
                            {
                                itemControl.BackColor = UCBackColor;
                            }
                        }
                        else
                        {
                            itemControl.BackColor = UCBackDefultColor;
                        }
                    }
                }

                shopUGrid.BackColor = UCClickColor;  //选中的颜色
                EliminateLattice = shopUGrid.Lattice as Lattice;
            }
        }

        #region  这两个方法已经不用
        ///// <summary>
        ///// 双击查看扫描信息
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //void latticeControl_DoubleClick(object sender, EventArgs e)
        //{
        //    if (splitContainerControl1.PanelVisibility == SplitPanelVisibility.Both)
        //    {
        //        splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel1;//只显示panel1
        //    }
        //    else
        //    {
        //        splitContainerControl1.PanelVisibility = SplitPanelVisibility.Both;//两个都可见
        //        ULattice control = sender as ULattice;
        //        Lattice model = control.Tag as Lattice;
        //        Getdata();
        //        OpenMess(model);// 展示信息
        //    }
        //   // InitialOutShopGrid();
        //}

        ///// <summary>
        ///// 单击事件
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //void latticeControl_Click(object sender, EventArgs e)
        //{
        //    foreach (UserControl cont in tableLayoutPanelOutOrder.Controls)
        //    {
        //        if (cont is ULattice)
        //        {
        //            ULattice itemControl = cont as ULattice;
        //            ULattice control = sender as ULattice;
        //            if (itemControl.Name == control.Name)
        //            {
        //                itemControl.BackColor = Color.Blue;
        //                EliminateLattice = itemControl.Tag as Lattice;
        //            }
        //            else
        //            {
        //                itemControl.BackColor = Color.WhiteSmoke;
        //            }
        //        }
        //    }           
        //}

        #endregion

        /// <summary>
        /// 扫描
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_Code_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (int)Keys.Enter)
            {
                if (string.IsNullOrEmpty(txt_Code.Text))
                {
                    return;
                }
                ExeCodeInfo();//执行扫描方法
            }
        }
        private string ConvertOrderBarCode(string strInput)
        {
            strInput = strInput.Trim();
            if (strInput.Length < 10)
            {
                if (Regex.IsMatch(strInput, "^[0-9]*$")) //验证是否为数字
                {
                    return "2" + strInput.PadLeft(9, '0');
                }
                else
                {
                    return null;
                }
            }
            else if (strInput.Length == 10 && strInput.StartsWith("2"))
            {
                return strInput;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 扫描方法
        /// </summary>
        private void ExeCodeInfo()
        {
            string code = ConvertOrderBarCode(txt_Code.Text.Trim());
            string mess = "";
            Lattice latt = new Lattice();

            int value = -1;
            try
            {
                //当InnerFactoryParameter.TechId=-1时，服务器没有检验当前流程是否在当前岗位，不是-1才检验当前流程是不是在此岗位上
                value = _LatticePartition.ScanningOrderInfoCode(InnerFactoryParameter.UserInfo.UserId, -1, code, InnterManagePresenter.latticePartitionModel.Pid, out latt, out mess);  //分配格子
                if (value == 0)
                {
                    //Getdata();
                    Lattice mdoel = GetGriddata(latt.LatticeID);
                    //InnterManagePresenter.latticePartitionModel.
                    EliminateLattice = mdoel;

                    Refreshdata(1, mdoel);
                         
                    BindGridControl(mdoel);                   
                }
                lbl_tisi.Text = mess;
                speech.Speak(mess);

                MapLocation();

                txt_Code.SelectAll();
            }
            catch (Exception ex)
            {
                WriteAnalyseLog.WriteLogFile(ex.Message);
            }
        }

        /// <summary>
        /// 定位
        /// </summary>
        public void MapLocation()
        {
            if (EliminateLattice != null)   //选择的不能为空
            {
                ULattice uclatticeControl = null;
                foreach (UserControl cont in tableLayoutPanelOutOrder.Controls)
                {
                    if (cont is ULattice)
                    {
                        ULattice itemControl = cont as ULattice;
                        if (itemControl.Name == EliminateLattice.LatticeID.ToString())
                        {
                            uclatticeControl = itemControl;
                            itemControl.BackColor = UCClickColor;
                            break;
                        }
                    }
                }
                if (uclatticeControl != null)  //当控件不为空时，定位
                {
                    int width = uclatticeControl.Location.X;
                    int height = uclatticeControl.Location.Y;
                    tableLayoutPanelOutOrder.AutoScrollPosition = new Point(width, height);
                }
            }
        }

        /// <summary>
        /// 刷新数据,0为从数据库加载 ，1 表示在内存中加上一个数量
        /// </summary>
        private void Refreshdata(int typeid, Lattice latt)
        {
            if (typeid == 0)
            {
                InnterManagePresenter.latticePartitionModel = _LatticePartition.GetLatticePartitionModel(InnterManagePresenter.FactoryId, Convert.ToInt32(Help.LatticePartitionID));
                InitialOutShopGrid();
            }
            else if (typeid == 1)
            {
                foreach (UserControl cont in tableLayoutPanelOutOrder.Controls)
                {
                    if (cont is ULattice)
                    {
                        ULattice itemControl = cont as ULattice;
                        Lattice model = itemControl.Tag as Lattice;
                        if (model.LatticeID == latt.LatticeID)
                        {
                            itemControl._ExistenceNumber++;
                            itemControl._OrderNumber = latt.OrderInfoCount;
                            itemControl.BackColor = Color.FromArgb(144, 233, 126);   //浅绿色
                            itemControl.Lattice = latt;
                            itemControl.Refreshdata();
                            return;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 确定按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_scanning_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_Code.Text))
            {
                //MessageBox.Show("请输入条码号！");

                lbl_tisi.Text = "请输入条码号！";
                speech.Speak("请输入条码号！");
                return;
            }
            ExeCodeInfo();//执行扫描方法
        }

        /// <summary>
        /// 清除格子里面的产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_Eliminate_Click(object sender, EventArgs e)
        {
            if (EliminateLattice == null )
            {
                MessageBox.Show("请选择需要清空的格子");
                speech.Speak("请选择需要清空的格子");
                return;
            }
            else
            {

            }
            string mess = "";
            int value = _LatticePartition.emptyLattice(EliminateLattice.LatticeID,out mess);
            speech.Speak(mess);
            if (value > 0)
            {
                foreach (UserControl cont in tableLayoutPanelOutOrder.Controls)
                {
                    if (cont is ULattice)
                    {
                        ULattice itemControl = cont as ULattice;
                        Lattice model = itemControl.Tag as Lattice;
                        if (model.LatticeID == EliminateLattice.LatticeID)
                        {
                            itemControl._ExistenceNumber = 0;
                            itemControl._OrderNumber = 0;

                            model.latticeRecordList = new List<LatticeRecord>();
                            model.OrderInfoCount = 0;
                            model.OrderID = 0;
                            model.State = 0;
                            model.OrderbagModel = new OrderBagInfo();
                            //  itemControl.Lattice = model;
                            itemControl.Refreshdata();
                            return;
                        }
                        else
                        {

                        }
                    }
                }
            }
        }
               
        /// <summary>
        /// 获取数据
        /// </summary>
        private void Getdata()
        {
            InnterManagePresenter.latticePartitionModel = _LatticePartition.GetLatticePartitionModel(InnterManagePresenter.FactoryId, Convert.ToInt32(Help.LatticePartitionID));
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        private Lattice GetGriddata(int ingridID)
        {
           return _LatticePartition.GetLatticeInfo(ingridID);
        }
        /// <summary>
        /// 绑定右边列表数据
        /// </summary>
        /// <param name="OrderBagInfo"></param>
        void BindGridControl(Lattice model)
        {
            if (model == null)
            {             
                return;
            }
            gridView_shopProduct.ClearSelection();
            string mess = "";
            OrderBagInfo OrderBag = _LatticePartition.GetOrderBag(model.OrderID, out mess);
            if (OrderBag != null)
            {
                model.OrderbagModel = OrderBag;

                txt_shopid.Text = OrderBag.ShopId.ToString();
                txt_shopname.Text = OrderBag.shopinfo.shopName;
                //txt_username.Text = OrderBag.orderinfoList[0].CtmName;
                txt_phone.Text = OrderBag.shopinfo.Tel1;
                txt_username.Text = OrderBag.shopinfo.shopKeeper;
                ULattice currLattice;
                _dictionaryControl.TryGetValue(model.LatticeID.ToString(), out currLattice);
                currLattice.Tag = model;
                //tableLayoutPanelOutOrder.Controls[model.LatticeID.ToString()].Tag = model;
                lbl_Count.Text = model.OrderInfoCount.ToString();
                foreach (OrderInfo info in OrderBag.orderinfoList)
                {
                    info.BagCode = model.OrderCode;
                    info.BagName = model.OrderName;
                    info.ShopName = info.orderBagInfo.ShopName;
                    info.CtmName = info.CtmName;
                    info.ProductName = info.prodinfo.ProductName;
                    info.ProductCode = info.prodinfo.ProductCode;
                    info.productNum = info.productNum;
                    info.OrderFetchTime = info.orderBagInfo.FetchTime;
                    info.oiStatus = GetStata(info);
                    if (model.latticeRecordList.Any(p => p.OrderInfoID == info.OrderProductId))
                    {
                        info.WhetherIn = "是";// 在格子中
                        info.IsPrint = true;
                    }
                    else
                    {
                        info.WhetherIn = "否";// 在格子中
                        info.IsPrint = false;
                    }                    
                }
                gridControlshopProduct.DataSource = OrderBag.orderinfoList.OrderByDescending(p => p.WhetherIn == "是").ToList();
            }
            else
            {
                txt_shopid.Text = "";
                txt_shopname.Text = "";
                txt_phone.Text = "";
                txt_username.Text = "";
                gridControlshopProduct.DataSource = null;
            }

            gridView_shopProduct.ClearSelection();
            
        }

        /// <summary>
        /// 设置颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView_shopProduct_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            int hand = e.RowHandle;
            if (hand < 0) return;
            OrderInfo dr = this.gridView_shopProduct.GetRow(hand) as OrderInfo;
            if (dr == null) return;
            if (dr.WhetherIn=="是")
            {
                //e.Appearance.ForeColor = Color.Red;// 改变行字体颜色
                e.Appearance.BackColor = Color.LawnGreen;// 改变行背景颜色
            }
            else
            {
                e.Appearance.BackColor = Color.White;// 改变行背景颜色
            }
        }
        
        /// <summary>
        ///  勾选操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView_shopProduct_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "IsPrint")
            {
                OrderInfo info = gridView_shopProduct.GetRow(e.RowHandle) as OrderInfo;
                if (info.WhetherIn == "是")
                {
                    
                }
                else
                {
                    info.IsPrint = false;
                    gridView_shopProduct.PostEditor();
                    gridControlshopProduct.RefreshDataSource();
                    gridControlshopProduct.Refresh();
                    //txt_Code.SelectAll();
                    txt_Code.Focus();
                }              
            }
        }


        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_Print_Click(object sender, EventArgs e)
        {
            try
            {
                bool b=false;  //

                List<OrderInfo> orderlist = new List<OrderInfo>();
                if (splitContainerControl1.PanelVisibility == SplitPanelVisibility.Both)   //方式一，勾选打印，不清格子
                {
                    int num=0;
                    for (int i = 0; i < gridView_shopProduct.RowCount; i++)
                    {
                        OrderInfo info = gridView_shopProduct.GetRow(i) as OrderInfo;
                        if (info.WhetherIn == "是" && info.IsPrint)
                        {
                            
                            orderlist.Add(info);
                        }
                        if(info.WhetherIn == "是"){
                            num++;
                        }

                    }
                    if (num == gridView_shopProduct.RowCount)
                    {
                        b = true;
                    }
                    if (orderlist.Count == 0)
                    {
                        //MessageBox.Show("请勾选需要打印的产品");

                        speech.Speak("请勾选需要打印的产品");
                        lbl_tisi.Text = "请勾选需要打印的产品";
                        return;
                    }
                }
                else   //方式二，直接打印
                {
                    if (EliminateLattice != null && EliminateLattice.OrderID > 0)
                    {
                        string mess = "";
                        OrderBagInfo OrderBag = _LatticePartition.GetOrderBag(EliminateLattice.OrderID, out mess);
                        if (OrderBag != null)
                        {
                            foreach (OrderInfo info in OrderBag.orderinfoList)
                            {
                                info.BagCode = EliminateLattice.OrderCode;
                                info.BagName = EliminateLattice.OrderName;
                                info.ShopName = info.orderBagInfo.ShopName;
                                info.CtmName = info.CtmName;
                                info.ProductName = info.prodinfo.ProductName;
                                info.ProductCode = info.prodinfo.ProductCode;
                                info.productNum = info.productNum;
                                info.OrderFetchTime = info.orderBagInfo.FetchTime;
                                if (EliminateLattice.latticeRecordList.Any(p => p.OrderInfoID == info.OrderProductId))
                                {
                                    orderlist.Add(info);
                                }
                            }
                        }
                    }
                    else
                    {
                        speech.Speak("请选择要打印的格子");
                        lbl_tisi.Text = "请选择要打印的格子";
                        return;
                    }
                }

                List<OrderInfo_Info> orderListPrint = new List<OrderInfo_Info>();// gcOrderInfo.DataSource as List<OrderInfo_Info>;                
                foreach (OrderInfo model in orderlist)
                {
                    OrderInfo_Info info=new OrderInfo_Info();
                    info.CtmName = model.CtmName;
                    info.CompleteTime = model.CompleteTime;
                    info.Height = model.Height;
                    info.OrderBagId = model.OrderBagId;
                    info.OrderPath = model.OrderPath;
                    info.OrderProductCode = model.OrderProductCode;
                    info.OrderProductId = model.OrderProductId;
                    info.OrderProductName = model.OrderProductName;
                    info.OrilOrderPath = model.OrilOrderPath;
                    info.PageNum = model.PageNum;
                    info.ParentProductId = model.ParentProductId;
                    info.PrePriceCount = model.PrePriceCount;
                    info.ProductId = model.ProductId;
                    info.ProductNum = model.productNum;
                    info.ProductType = model.ProductType;
                    info.Remark = model.Remark;
                    info.ShopName = model.ShopName;
                    info.Status = model.Status;
                    info.Width = model.Width;
                    orderListPrint.Add(info);
                }

                if (orderListPrint != null && orderListPrint.Count > 0)
                {
                    string mess = "";
                    _presenter.PrintShopBill(InnerFactoryParameter.TechId, InnerFactoryParameter.UserInfo.UserId, orderListPrint, true, 0,out mess);
                    lbl_tisi.Text = mess;
                    speech.Speak(mess);
                    if (string.IsNullOrEmpty(mess))
                    {

                        if (splitContainerControl1.PanelVisibility == SplitPanelVisibility.Both)   //方式一，勾选打印，不清格子
                        {
                            if (b)  //全部产品已经做完
                            {
                                if (EliminateLattice != null)
                                {
                                    but_Eliminate_Click(null, null);//清理格子
                                }
                                else
                                {
                                    //清理格子失败
                                    lbl_tisi.Text = "清理格子失败";
                                    speech.Speak("清理格子失败");
                                }
                            }
                        }
                        else    //
                        {
                            if (EliminateLattice != null)
                            {
                                but_Eliminate_Click(null, null);//清理格子
                            }
                            else
                            {
                                //清理格子失败
                                lbl_tisi.Text = "清理格子失败";
                                speech.Speak("清理格子失败");
                            }
                        }

                    }
                }
                else
                {
                    MessageBox.Show("无账单可以打印！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 重打
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_Wham_Click(object sender, EventArgs e)
        {
            try
            {
                _presenter.RePrint();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public void LinkOrderInfo(List<OrderInfo_Info> orderInfo)
        {
          
        }

        /// <summary>
        /// 标记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_sign_Click(object sender, EventArgs e)
        {
            FrmTpyeSelect select = new FrmTpyeSelect();
            select.ShowDialog();
        
            if (select.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                    string shopname = select.ShopName;
                ULattice uclatticeControl = null;
                foreach (UserControl cont in tableLayoutPanelOutOrder.Controls)
                {
                    if (cont is ULattice)
                    {
                        ULattice itemControl = cont as ULattice;
                        Lattice model = itemControl.Tag as Lattice;

                        if ( model.OrderbagModel!=null )
                        {
                            if (!string.IsNullOrEmpty(model.OrderbagModel.ShopName) && model.OrderbagModel.ShopName.Contains(shopname) || (model.OrderbagModel.ctmNames.Contains(shopname)))
                            {
                                if (uclatticeControl == null)
                                {
                                    uclatticeControl = itemControl;
                                }
                                cont.BackColor = UCClickColor;
                            }
                        }
                        else
                        {

                        }
                    }
                }
                if (uclatticeControl != null)  //当控件不为空时，定位
                {
                    int width = uclatticeControl.Location.X;
                    int height = uclatticeControl.Location.Y;
                    tableLayoutPanelOutOrder.AutoScrollPosition = new Point(width, height);
                }
            }
            else
            {
                MessageBox.Show("取消了操作！");
            }
        }

        /// <summary>
        /// 全选/全不选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_Select_Click(object sender, EventArgs e)
        {

            List<OrderInfo> lit = (List<OrderInfo>)gridControlshopProduct.DataSource;
                
            for (int i = 0; i < gridView_shopProduct.RowCount; i++)
            {
                OrderInfo model = gridView_shopProduct.GetRow(i) as OrderInfo;
                if (model.WhetherIn == "是")
                {
                    lit.FirstOrDefault(p => p.OrderProductId == model.OrderProductId).IsPrint = !(bool)but_Select.Tag;
                    model.IsPrint = !(bool)but_Select.Tag;
                }
                else
                {

                }
            }
            but_Select.Tag = !(bool)but_Select.Tag;
            gridControlshopProduct.DataSource = lit;

            gridControlshopProduct.RefreshDataSource();
            gridControlshopProduct.Refresh();
        }

        /// <summary>
        /// 改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void com_Lattice_SelectedIndexChanged(object sender, EventArgs e)
        {
            LatticePartition model = com_LatticePartition.SelectedItem as LatticePartition;

            txt_Code.Focus();

            if (InnterManagePresenter.latticePartitionModel != null )
            {
               
                if (InnterManagePresenter.latticePartitionModel.Pid != model.Pid && model != null)
                {
                    Help.LatticePartitionID = model.Pid.ToString();
                    Getdata();
                    //InnterManagePresenter.latticePartitionModel = model;                   
                    LoadControl();
                }
            }
            else
            {
                InnterManagePresenter.latticePartitionModel = model;
                Help.LatticePartitionID = model.Pid.ToString();
                LoadControl();
            }
        }
        
        /// <summary>
        /// 绑定数据
        /// </summary>
        private void Bind()
        {
            listData = _LatticePartition.GetLatticePartitionList(InnterManagePresenter.FactoryId);
            BindComControl();
            BindPar();
        }

        List<LatticePartition> listData = new List<LatticePartition>();

        /// <summary>
        /// 绑定所有数据
        /// </summary>
        private void BindComControl()
        {
            com_LatticePartition.Properties.Items.Clear();
            foreach (LatticePartition model in listData)
            {
                com_LatticePartition.Properties.Items.Add(model);
            }            
        }


        public void BindPar()
        {
            if (!string.IsNullOrEmpty(Help.LatticePartitionID))
            {
                InnterManagePresenter.latticePartitionModel = listData.FirstOrDefault(p => p.Pid == Convert.ToInt32(Help.LatticePartitionID));
            }
            if (InnterManagePresenter.latticePartitionModel != null && InnterManagePresenter.latticePartitionModel.Pid > 0)
            {
                com_LatticePartition.Text = InnterManagePresenter.latticePartitionModel.LatticeHeadName;
            }
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton8_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmMain_KeyPress(object sender, KeyPressEventArgs e)
        {
           
        }
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
        {

            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN)
            {
                switch (keyData)
                {
                    case Keys.Escape:
                        splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel1;//先收缩右边的详细列表
                        break;
                }
            }
            return false;
        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmClosed();
        }       
        
        private void frmClosed()
        {
            try
            {              
                this.Dispose();
                Application.Exit();
                Application.ExitThread();
                System.Environment.Exit(System.Environment.ExitCode);
            }
            catch (Exception ex)
            {
                WriteAnalyseLog.WriteLogFile(DateTime.Now + ex.Message);
            }
        }
    }
}
